package service

import (
	"context"
	"errors"
	"strconv"

	"bmember/internal/dao"

	"bmember/internal/conf"
	"bmember/pkg/log"
	"bmember/pkg/lueerror"
)

// Service 逻辑处理层
type Service struct {
	logger log.Factory
	cfg    *conf.Config
}

var service *Service

// InitService 初始化逻辑处理对象
func InitService(logger log.Factory, cfg *conf.Config) {
	service = &Service{
		logger: logger,
		cfg:    cfg,
	}
}

// GetService 获得逻辑层基础定义
func GetService() *Service {
	return service
}

func parseLueerror(err error) lueerror.LueError {
	if err != nil {
		lueErr, ok := err.(lueerror.LueError)
		if ok {
			return lueErr
		} else {
			return lueerror.DbErr(err)
		}
	}
	return nil
}

// IdParse id string to int64
func (srv *Service) IdParse(id string) (int64, lueerror.LueError) {
	if id == "" {
		return 0, nil
	}
	ret, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		return 0, lueerror.InvalidRequest(err)
	}
	return ret, nil
}

// SendMobileVerifyCode 发送短信验证码
func (srv *Service) SendMobileVerifyCode(ctx context.Context, mobile, codeType string) lueerror.LueError {
	err := dao.GetBilinVendorDao().SendMobileCode(ctx, mobile, codeType)
	if err != nil {
		return lueerror.MqErr(err)
	}
	return nil
}

// VerifyMobileCode 短信验证
func (srv *Service) VerifyMobileCode(ctx context.Context, mobile, codeType, code string) lueerror.LueError {
	if srv.cfg.Base.Debug && code == "6666" {
		return nil
	}
	ok, err := dao.GetBilinVendorDao().VerifyMobileCode(ctx, mobile, code, codeType)
	if err != nil {
		return lueerror.BilinSmsErr(err)
	}
	if !ok {
		return lueerror.CodeVerifyFailed(errors.New("验证码错误"))
	}
	return nil
}
